package com.shenmazong.serverwebpoem.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.code.kaptcha.Constants;
import com.shenmazong.serverwebpoem.pojo.*;
import com.shenmazong.serverwebpoem.service.*;
import com.shenmazong.serverwebpoem.util.IpUtil;
import com.shenmazong.serverwebpoem.util.ParamUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 田不平
 * @project server-web-poem
 * @date 2020/3/24 11:59 AM
 * http://www.shenmazong.com
 */

@Slf4j
@Controller
@RequestMapping(value = "/")
public class PoetryController {

    @Autowired
    TbPoetryService tbPoetryService;

    @Autowired
    TbTranslateService tbTranslateService;

    @Autowired
    TbNoteService tbNoteService;

    @Autowired
    TbAppreciationService tbAppreciationService;

    @Autowired
    TbStoryService tbStoryService;

    @Autowired
    TbUserService tbUserService;

    @Autowired
    TbPoetryInfoService tbPoetryInfoService;

    @Autowired
    TbCollectionService tbCollectionService;


    //TbPoetry(id=1, title=三秦民谣, dyid=1, dynasty=秦, authorid=1, author=无名氏, content=武功太白，去天三百。孤云两角，去天一握。山水险阻，黄金子午。蛇盘鸟栊，势与天通。, createtime=2020-03-19 12:41:17)

    /**
     * TODO 首页展示
     * @param model
     * @return
     */
    @GetMapping(value = {"/", "/index"})
    public String index(Model model) {

        //IPage<TbPoetry> iPage = tbPoetryService.getListByPage(1, 5);
        //List<TbPoetry> poetries = iPage.getRecords();

        IPage<Map<String, Object>> iPage = tbPoetryService.getMapPoetryByPage(1, 5);
        List<Map<String, Object>> poetries = iPage.getRecords();


        model.addAttribute("poetries", poetries);

        model.addAttribute("pageCurrent", 1);
        model.addAttribute("pageSize", 5);
        model.addAttribute("pageCount", iPage.getPages());
        model.addAttribute("count", iPage.getTotal());

        // 分页数据
        List<Integer> pages = new ArrayList<>();
        for(Integer idx=1; idx<8; idx++) {
            if(idx>iPage.getPages())
                break;
            pages.add(idx);
        }
        model.addAttribute("pages", pages);

        // 获取登录用户信息
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        if(user != null) {
            model.addAttribute("user", user);
        }

        return "index";
    }

    /**
     * TODO 列表页展示
     * @param model
     * @param pageNo
     * @return
     */
    @GetMapping(value = "/list/{pageNo}")
    public String list(Model model, @PathVariable(name = "pageNo") Integer pageNo) {
//        IPage<TbPoetry> iPage = tbPoetryService.getListByPage(pageNo, 5);
//        List<TbPoetry> poetries = iPage.getRecords();
        IPage<Map<String, Object>> iPage = tbPoetryService.getMapPoetryByPage(pageNo, 5);
        List<Map<String, Object>> poetries = iPage.getRecords();

        model.addAttribute("poetries", poetries);
        model.addAttribute("pageCurrent", pageNo);
        model.addAttribute("pageSize", 5);
        model.addAttribute("pageCount", iPage.getPages());
        model.addAttribute("count", iPage.getTotal());

        if(pageNo < 5) {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=1; idx<8; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }
        else {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=pageNo-3; idx<pageNo+4; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }

        // 获取登录用户信息
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        if(user != null) {
            model.addAttribute("user", user);
        }

        return "index";
    }

    @GetMapping(value = "/hots/{pageNo}")
    public String hots(Model model, @PathVariable(name = "pageNo") Integer pageNo) {
        IPage<Map<String, Object>> iPage = tbPoetryService.getMapPoetry4ClickByPage(pageNo, 5);
        List<Map<String, Object>> poetries = iPage.getRecords();

        model.addAttribute("poetries", poetries);
        model.addAttribute("pageCurrent", pageNo);
        model.addAttribute("pageSize", 5);
        model.addAttribute("pageCount", iPage.getPages());
        model.addAttribute("count", iPage.getTotal());

        if(pageNo < 5) {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=1; idx<8; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }
        else {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=pageNo-3; idx<pageNo+4; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }

        // 获取登录用户信息
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        if(user != null) {
            model.addAttribute("user", user);
        }

        return "hots";
    }

    /**
     * TODO 根据作者ID显示作者的所有作品
     * @param model
     * @param id
     * @return
     */
    @GetMapping(value = "/author/{id}/{pageNo}")
    public String author(Model model,
                         @PathVariable(name = "id") Integer id,
                         @PathVariable(name = "pageNo") Integer pageNo) {

//        IPage<TbPoetry> iPage = tbPoetryService.getListByAuthorId(id, pageNo, 5);
//        List<TbPoetry> poetries = iPage.getRecords();

        IPage<Map<String, Object>> iPage = tbPoetryService.getMapPoetry4AuthorByPage(id, pageNo, 5);
        List<Map<String, Object>> poetries = iPage.getRecords();
        log.info("count={}", poetries.size());

        model.addAttribute("poetries", poetries);
        model.addAttribute("pageCurrent", pageNo);
        model.addAttribute("pageSize", 5);
        model.addAttribute("pageCount", iPage.getPages());
        model.addAttribute("count", iPage.getTotal());

        model.addAttribute("authorId", id);

        if(pageNo < 5) {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=1; idx<8; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }
        else {
            List<Integer> pages = new ArrayList<>();
            for(Integer idx=pageNo-3; idx<pageNo+4; idx++) {
                if(idx>iPage.getPages())
                    break;
                pages.add(idx);
            }
            model.addAttribute("pages", pages);
        }

        // 获取登录用户信息
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        if(user != null) {
            model.addAttribute("user", user);
        }

        return "index";
    }

    /**
     * TODO 根据诗词的ID显示诗词的详细页面
     * @param model
     * @param id
     * @return
     */
    @GetMapping(value = "/poetry/{id}")
    public String poetry(Model model, @PathVariable(name = "id") Integer id) {
        List<Integer> nothing = new ArrayList<>();

        //-- 获取诗词
        TbPoetry poetry = tbPoetryService.getPoetryById(id);
        if(poetry == null) {
            return "error-403";
        }
        model.addAttribute("poetry", poetry);

        //-- 获取注释
        List<TbNote> notes = tbNoteService.getByPoetryId(id);
        if(notes == null || notes.size() == 0) {
            model.addAttribute("notes", nothing);
        }
        else {
            model.addAttribute("notes", notes);
        }

        //-- 获取译文
        List<TbTranslate> translates = tbTranslateService.getByPoetryId(id);
        if(translates == null || translates.size() == 0) {
            model.addAttribute("translates", nothing);
        }
        else {
            model.addAttribute("translates", translates);
        }

        //-- 获取赏析
        List<TbAppreciation> appreciations = tbAppreciationService.getByPoetryId(id);
        if(appreciations == null || appreciations.size() == 0) {
            model.addAttribute("appreciations", nothing);
        }
        else {
            model.addAttribute("appreciations", appreciations);
        }

        //-- 获取故事
        List<TbStory> stories = tbStoryService.getByPoetryId(id);
        if(stories == null || stories.size() == 0) {
            model.addAttribute("stories", nothing);
        }
        else {
            model.addAttribute("stories", stories);
        }

        //-- 增加点击率
        TbPoetryInfo poetryInfo = tbPoetryInfoService.getByPoetryId(id);
        if(poetryInfo == null) {
            poetryInfo = new TbPoetryInfo();
            poetryInfo.setPoetryid(id);
            poetryInfo.setClicks(1);

            tbPoetryInfoService.add(poetryInfo);
            poetryInfo = tbPoetryInfoService.getByPoetryId(id);
        }
        else {
            poetryInfo.setClicks(poetryInfo.getClicks()+1);
            tbPoetryInfoService.set(poetryInfo);
        }
        model.addAttribute("poetryInfo", poetryInfo);

        // 获取登录用户信息
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        if(user != null) {
            model.addAttribute("user", user);
        }

        return "detail";
    }

    /**
     * TODO 跳转到添加注释
     * @return
     */
    @GetMapping(value = "/goNote/{id}")
    public String goNote(Model model, @PathVariable(name = "id") Integer id) {

        TbPoetry poetry = tbPoetryService.getPoetryById(id);
        if(poetry == null) {
            return "index";
        }

        model.addAttribute("poetry", poetry);

        // 获取登录用户信息
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        if(user != null) {
            model.addAttribute("user", user);
        }

        return "note";
    }

    /**
     * TODO 添加注释
     * @return
     */
    @PostMapping(value = "/doNote")
    public String doNote(HttpServletRequest request, Model model) {

        String poetryId = request.getParameter("poetryid");
        if(poetryId == null || poetryId.length() == 0) {
            return "index";
        }

        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        if(user == null) {
            return "redirect:/poetry/" + poetryId;
        }


        String content = request.getParameter("mynote");
        String title = request.getParameter("title");
        Integer userid = user.getId();

        TbNote note = new TbNote();
        note.setPoetryid(Integer.parseInt(poetryId));
        note.setUserid(userid);
        note.setNickname(user.getNickname());
        note.setTitle(title);
        note.setContent(content);

        tbNoteService.add(note);
        if(note.getId() > 0) {
            return "redirect:/poetry/" + poetryId;
        }

        return "redirect:/goNote/" + poetryId;
    }

    /**
     * TODO 跳转到添加译文
     * @return
     */
    @GetMapping(value = "/goTranslate/{id}")
    public String goTranslate(Model model, @PathVariable(name = "id") Integer id) {
        TbPoetry poetry = tbPoetryService.getPoetryById(id);
        if(poetry == null) {
            return "index";
        }

        model.addAttribute("poetry", poetry);

        // 获取登录用户信息
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        if(user != null) {
            model.addAttribute("user", user);
        }

        return "translate";
    }

    /**
     * TODO 添加译文
     * @param request
     * @param model
     * @return
     */
    @PostMapping(value = "/doTranslate")
    public String doTranslate(HttpServletRequest request, Model model) {

        String poetryId = request.getParameter("poetryid");
        if(poetryId == null || poetryId.length() == 0) {
            return "index";
        }

        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        if(user == null) {
            return "redirect:/goTranslate/" + poetryId;
        }


        String content = request.getParameter("content");
        String title = request.getParameter("title");
        Integer userid = user.getId();

        TbTranslate translate = new TbTranslate();
        translate.setPoetryid(Integer.parseInt(poetryId));
        translate.setUserid(userid);
        translate.setNickname(user.getNickname());
        translate.setTitle(title);
        translate.setContent(content);

        tbTranslateService.add(translate);
        if(translate.getId() > 0) {
            return "redirect:/poetry/" + poetryId;
        }

        return "redirect:/goTranslate/" + poetryId;
    }

    /**
     * TODO 跳转到添加赏析
     * @return
     */
    @GetMapping(value = "/goAppreciation/{id}")
    public String goAppreciation(Model model, @PathVariable(name = "id") Integer id) {
        TbPoetry poetry = tbPoetryService.getPoetryById(id);
        if(poetry == null) {
            return "index";
        }

        model.addAttribute("poetry", poetry);

        // 获取登录用户信息
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        if(user != null) {
            model.addAttribute("user", user);
        }

        return "appreciation";
    }

    /**
     * TODO 添加赏析
     * @return
     */
    @PostMapping(value = "/doAppreciation")
    public String doAppreciation(HttpServletRequest request, Model model) {
        String poetryId = request.getParameter("poetryid");
        if(poetryId == null || poetryId.length() == 0) {
            return "index";
        }

        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        if(user == null) {
            return "redirect:/goAppreciation/" + poetryId;
        }


        String content = request.getParameter("content");
        String title = request.getParameter("title");
        Integer userid = user.getId();

        TbAppreciation appreciation = new TbAppreciation();
        appreciation.setPoetryid(Integer.parseInt(poetryId));
        appreciation.setUserid(userid);
        appreciation.setNickname(user.getNickname());
        appreciation.setTitle(title);
        appreciation.setContent(content);

        tbAppreciationService.add(appreciation);
        if(appreciation.getId() > 0) {
            return "redirect:/poetry/" + poetryId;
        }

        return "redirect:/goAppreciation/" + poetryId;
    }

    /**
     * TODO 跳转到添加故事
     * @return
     */
    @GetMapping(value = "/goStory/{id}")
    public String goStory(Model model, @PathVariable(name = "id") Integer id) {
        TbPoetry poetry = tbPoetryService.getPoetryById(id);
        if(poetry == null) {
            return "index";
        }

        model.addAttribute("poetry", poetry);

        // 获取登录用户信息
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        if(user != null) {
            model.addAttribute("user", user);
        }

        return "story";
    }

    /**
     * TODO 添加故事
     * @return
     */
    @PostMapping(value = "/doStory")
    public String doStory(HttpServletRequest request, Model model) {
        String poetryId = request.getParameter("poetryid");
        if(poetryId == null || poetryId.length() == 0) {
            return "index";
        }

        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        if(user == null) {
            return "redirect:/goStory/" + poetryId;
        }


        String content = request.getParameter("content");
        String title = request.getParameter("title");
        Integer userid = user.getId();

        TbStory story = new TbStory();
        story.setPoetryid(Integer.parseInt(poetryId));
        story.setUserid(userid);
        story.setNickname(user.getNickname());
        story.setTitle(title);
        story.setContent(content);

        tbStoryService.add(story);
        if(story.getId() > 0) {
            return "redirect:/poetry/" + poetryId;
        }

        return "redirect:/goStory/" + poetryId;
    }
}
